import datetime
import random
from django.views import View
from django.http import HttpResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from django_redis import get_redis_connection
from user.models import User
from user.serializers import UserSerializer, UserUnActiveSerializer


# 验证用户信息唯一性
class RegCountView(APIView):
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        # 接受参数 验证的内容 type: username/phone/email,  data: '用户名' 或者 '手机号',

        datatype = request.data.get('type')
        data = request.data.get('data')
        if not all([datatype, data]):
            return Response({'code': 999, 'msg': "参数不全"})
        if datatype == 'username':
            count = User.objects.filter(username=data).count()
        if datatype == 'phone':
            count = User.objects.filter(phone=data).count()
        if datatype == 'email':
            count = User.objects.filter(email=data).count()

        return Response({'code': 0, 'msg': '查询成功', 'data': {'type': datatype, 'count': count}})


class RegisterVIew(APIView):
    '''用户注册，权限是，匿名用户可以访问'''
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        '''接受邮箱和密码，前端校验两遍一致性，注册成功返回成功，用户自己登录
        1.随机用户名
        2.生成用户
        3.设置用户密码
        4.保存用户
        :param request
        :return {"code":0,"msg":"注册成功"}
        '''
        username = request.data.get('username')
        phone = request.data.get('phone')
        code = request.data.get('code')
        passwrod = request.data.get('password')

        if all([username, passwrod, phone, code]):
            pass
        else:
            return Response({'code': 404, 'msg': '参数不全'})

        # rand_name = self.randomUsername()

        # 验证手机验证码
        redis_client = get_redis_connection('verify_code')
        code_redis = redis_client.get(phone)
        if code_redis:
            code_redis = code_redis.decode()

        if not code == code_redis:
            return Response({'code': 999, 'msg': '手机验证码错误'})

        user = User(username=username, phone=phone)
        user.set_password(passwrod)
        user.save()

        return Response({'code': 0, 'msg': '注册成功'})

    def randomUsername(self):
        """
        生成随机用户名: 格式: SYL + 年月日时分 + 5位随机数
        :return:
        """
        d = datetime.datetime.now()
        base = 'SYL'
        time_str = '%04d%02d%02d%02d%02d' % (d.year, d.month, d.day, d.hour, d.minute)
        rand_num = str(random.randint(10000, 99999))
        return base + time_str + rand_num


def index(request):
    # 需要认证才能访问的视图
    return HttpResponse('hello')


class IndexView(View):
    # 普通类视图, 没有权限验证功能
    def get(self, request):
        return HttpResponse('类视图')


class ApiView(APIView):
    # APIView默认有认证,权限功能
    # authentication_classes = (JSONWebTokenAuthentication,)  # 默认配置,可不写, 可自定义
    # permission_classes = (IsAuthenticated,)  # 默认配置,可不写, 可自定义

    def get(self, request):
        return Response({"msg": "APIView"})


# 自定义分页器 局部
class PageNum(PageNumberPagination):
    # 查询字符串中代表每页返回数据数量的参数名, 默认值: None
    page_size_query_param = 'page_size'
    # 查询字符串中代表页码的参数名, 有默认值: page
    # page_query_param = 'page'
    # 一页中最多的结果条数
    max_page_size = 2


class MyPermission(BasePermission):
    def has_permission(self, request, view):
        """判断用户对模型有没有访问权"""
        if request.user.is_superuser:
            # 管理员对用户模型有访问权
            return True
        elif view.kwargs.get('pk') == str(request.user.id):
            # 携带的id和用户的id相同时有访问权
            return True
        return False


# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
    """
    完成产品的增删改查
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer  # 优先使用 get_serializer_class 返回的序列化器

    # 自定义认证类, 自定义会覆盖全局配置
    # authentication_classes = (JSONWebTokenAuthentication,)
    # 自定义权限类
    permission_classes = (MyPermission,)
    # 自定义限流类
    throttle_classes = [UserRateThrottle]

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('date_joined', 'id')

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('username', 'phone', 'is_active')

    # 自定义分页器 覆盖全局配置
    # pagination_class = PageNum

    # 根据不同的请求, 获得不同的序列化器
    def get_serializer_class(self):
        # print(self.context)
        # if self.action == 'partial_update':
        #     return ProductPartialUpdateSerializer
        if self.action == 'unactived':
            return UserUnActiveSerializer
        else:
            return UserSerializer

    # 自定义action
    @action(methods=['get'], detail=False)
    def unactived(self, request, *args, **kwargs):
        # 获取查询集, 过滤出未激活的用户
        qs = self.queryset.filter(is_active=False)
        # 使用序列化器, 序列化查询集, 并且是
        ser = self.get_serializer(qs, many=True)

        return Response(ser.data)
